import { createSlice } from '@reduxjs/toolkit'
import axios from 'axios'
const todomvc = createSlice({
  name: 'todomvc',
  initialState: {
    list: [],
    types: 'all',
  },
  reducers: {
    getList: (state, action) => {
      state.list = action.payload
    },
    addList: (state, action) => {
      state.list = [...state.list, action.payload]
    },
    delList: (state, action) => {
      state.list = state.list.filter((item) => item.id !== action.payload)
    },
    //修改状态
    changeList: (state, action) => {
      state.list[action.payload.id - 1].done = action.payload.checked
    },
    changeNameList: (state, action) => {
      state.list[action.payload.id - 1].name = action.payload.name
    },
    //修改底部状态
    changeFilter: (state, action) => {
      state.types = action.payload
    },
  },
})

export const {
  getList,
  addList,
  delList,
  changeList,
  changeNameList,
  changeFilter,
} = todomvc.actions
//发送请求
export const getListAsync = () => {
  return async (dispatch) => {
    const res = await axios.get('http://localhost:8888/todos')
    // console.log(res.data)
    dispatch(getList(res.data))
  }
}

//添加任务
export const addTodo = (name) => {
  return async (dispatch) => {
    const res = await axios.post('http://localhost:8888/todos', {
      name,
      done: false,
    })
    dispatch(addList(res.data))
  }
}
//删除任务
export const delTodo = (id) => {
  return async (dispatch) => {
    await axios.delete(`http://localhost:8888/todos/` + id)
    dispatch(delList(id))
  }
}
//任务状态改变
export const changeDone = (id, checked) => {
  return async (dispatch) => {
    await axios.patch(`http://localhost:8888/todos/` + id, { done: checked })
    //最简单写法
    // dispatch(getListAsync())
    dispatch(changeList({ id, checked }))
  }
}

export const changeName = (id, name) => {
  return async (dispatch) => {
    await axios.patch(`http://localhost:8888/todos/` + id, { name })
    //最简单写法
    // dispatch(getListAsync())
    dispatch(changeNameList({ id, name }))
  }
}

export default todomvc.reducer
